package org.jeecg.modules.demo.caiWuSkd.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.caiWuSkd.entity.CwSkd;
import org.jeecg.modules.demo.caiWuSkd.mapper.CwSkdMapper;
import org.jeecg.modules.demo.caiWuSkd.service.ICwSkdService;
import org.jeecg.modules.demo.cwSaleInvoice.entity.CwSaleInvoice;
import org.jeecg.modules.demo.cwSaleInvoice.mapper.CwSaleInvoiceMapper;
import org.jeecg.modules.demo.soSaleOrder.entity.SoSaleOrder;
import org.jeecg.modules.demo.soSaleOrder.mapper.SoSaleOrderMapper;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.jeecg.modules.demo.yxqcysOrder.entity.YxQcysOrder;
import org.jeecg.modules.demo.yxqcysOrder.mapper.YxQcysOrderMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: cw_skd
 * @Author: jeecg-boot
 * @Date: 2021-12-14
 * @Version: V1.0
 */
@Service
public class CwSkdServiceImpl extends ServiceImpl<CwSkdMapper, CwSkd> implements ICwSkdService {

    @Resource
    private CwSkdMapper cwSkdMapper;
    @Resource
    private SoSaleOrderMapper soSaleOrderMapper;
    @Resource
    private ISysBaseAPI sysBaseAPI;
    @Resource
    private CwSaleInvoiceMapper cwSaleInvoiceMapper;
    @Resource
    private YxQcysOrderMapper yxQcysOrderMapper;

    private String getMessage(String name, String date) {
        String str = "由【" + name + "】于【" + date + "】发起的预收款单需要您的审核，请及时查看！";
        return str;
    }

    private static final String TITLE = "单据审核";

    @Override
    public String getMaxCode() {
        return cwSkdMapper.getMaxCode();
    }

    @Override
    @Transactional
    public boolean addQcYskd(JSONObject jsonObject, HttpServletRequest req) {
        try {
            SoSaleOrder cwSkdi = JSON.parseObject(jsonObject.toJSONString(), SoSaleOrder.class);
            CwSkd cwSkd = JSON.parseObject(jsonObject.toJSONString(), CwSkd.class);


            String max_code = cwSkdMapper.getMaxCode();

            Map<String, String> codeMap = new HashMap<>();
            if (max_code == null) {
                codeMap.put("maxCode", null);
            } else {
                codeMap.put("maxCode", max_code);
            }
            String tenantId = req.getHeader("tenant-id");
            String tname = soSaleOrderMapper.getTname(tenantId);
            String name = tname + "QCYSK_";
            String xssk = generateOddUtil.createCode(codeMap, name);
            cwSkd.setId("");
            cwSkd.setSkNo(xssk);
//			cwSkd.setSosNo(cwSkdi.getSosNo());
//			String soSaleOrder = soSettlementService.getBySosNo(cwSkdi.getSosNo());
//            cwSkd.setFpNo(cwSkdi.getInvoiceNo());
            cwSkd.setSkJinen(cwSkd.getSkJinee());
//            cwSkd.setJsType(cwSkdi.getJsType());
//			cwSkd.setZhName(cwSkdi.getZhName());
//			cwSkd.setSkJine(cwSkdi.getSkJine());
//            cwSkd.setSoNo(cwSkdi.getSoNo());
//            cwSkd.setYwName(cwSkdi.getPoStaff());
            cwSkd.setJsCustom(cwSkdi.getSoCustom());
            cwSkd.setSosNum(cwSkdi.getSoTotail());
            cwSkd.setSosPrice(cwSkdi.getHsdj());
            cwSkd.setSosAmount(cwSkdi.getHsje());
            cwSkd.setSosNotax(cwSkdi.getWsje());
            cwSkd.setIsDelete(0);
            cwSkd.setSoStatus(0);
            cwSkd.setYwType("6");
            cwSkd.setBjJine(cwSkd.getSkJinen());
            cwSkd.setYwName(cwSkdi.getSoStaff());
            if (cwSkd.getPuCdate() == null) {
                cwSkd.setPuCdate(new Date());
            }
            cwSkdMapper.insert(cwSkd);
            SoSaleOrder sso = soSaleOrderMapper.getBysoNo(cwSkdi.getSoOrder());
            if (sso.getYskJine() == null) {
                sso.setYskJine(BigDecimal.valueOf(0).add(cwSkd.getSkJinen()));
            } else {
                sso.setYskJine(sso.getYskJine().add(cwSkd.getSkJinen()));
            }
            soSaleOrderMapper.updateById(sso);
//			cwSkdi.setIsSkd(1);
//			cwSaleInvoiceService.updateById(cwSkdi)


            LoginUser user = sysBaseAPI.getUserById(cwSkd.getYwName());
            TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
            templateMessageDTO.setFromUser("管理员");
            templateMessageDTO.setToUser(cwSkd.getShName() + ",");
            templateMessageDTO.setTitle(TITLE);
            templateMessageDTO.setTemplateCode("order");
            Map<String, String> templateParam = new HashMap<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String str = simpleDateFormat.format(new Date());
            templateParam.put("ts_date", str);
            templateParam.put("ts_content", getMessage(user != null?user.getRealname():"该业务员不存在！", str));
            templateParam.put("checkOrder", cwSkd.getSkNo());
            templateParam.put("cd_url", "/yunxiao/collection/CwYskdList");
            templateMessageDTO.setTemplateParam(templateParam);
            sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;

        }
    }

    @Override
    @Transactional
    public boolean addYskd(JSONObject jsonObject, HttpServletRequest req) {
        try {
            SoSaleOrder cwSkdi = JSON.parseObject(jsonObject.toJSONString(), SoSaleOrder.class);
            CwSkd cwSkd = JSON.parseObject(jsonObject.toJSONString(), CwSkd.class);


            String max_code = cwSkdMapper.getMaxCode();

            Map<String, String> codeMap = new HashMap<>();
            if (max_code == null) {
                codeMap.put("maxCode", null);
            } else {
                codeMap.put("maxCode", max_code);
            }
            String tenantId = req.getHeader("tenant-id");
            String tname = soSaleOrderMapper.getTname(tenantId);
            String name = tname + "SK_";
            String xssk = generateOddUtil.createCode(codeMap, name);
            cwSkd.setId("");
            cwSkd.setSkNo(xssk);
//			cwSkd.setSosNo(cwSkdi.getSosNo());
//			String soSaleOrder = soSettlementService.getBySosNo(cwSkdi.getSosNo());
//            cwSkd.setFpNo(cwSkdi.getInvoiceNo());
            cwSkd.setSkJinen(cwSkd.getSkJinee());
//            cwSkd.setJsType(cwSkdi.getJsType());
//			cwSkd.setZhName(cwSkdi.getZhName());
//			cwSkd.setSkJine(cwSkdi.getSkJine());
//            cwSkd.setSoNo(cwSkdi.getSoNo());
//            cwSkd.setYwName(cwSkdi.getPoStaff());
            cwSkd.setJsCustom(cwSkdi.getSoCustom());
            cwSkd.setSosNum(cwSkdi.getSoTotail());
            cwSkd.setSosPrice(cwSkdi.getHsdj());
            cwSkd.setSosAmount(cwSkdi.getHsje());
            cwSkd.setSosNotax(cwSkdi.getWsje());
            cwSkd.setIsDelete(0);
            cwSkd.setSoStatus(0);
            cwSkd.setYwType("2");
            cwSkd.setBjJine(cwSkd.getSkJinen());
            cwSkd.setYwName(cwSkdi.getSoStaff());
            if (cwSkd.getPuCdate() == null) {
                cwSkd.setPuCdate(new Date());
            }
            cwSkdMapper.insert(cwSkd);
            SoSaleOrder sso = soSaleOrderMapper.getBysoNo(cwSkdi.getSoOrder());
            if (sso.getYskJine() == null) {
                sso.setYskJine(BigDecimal.valueOf(0).add(cwSkd.getSkJinen()));
            } else {
                sso.setYskJine(sso.getYskJine().add(cwSkd.getSkJinen()));
            }
            soSaleOrderMapper.updateById(sso);
//			cwSkdi.setIsSkd(1);
//			cwSaleInvoiceService.updateById(cwSkdi)


            LoginUser user = sysBaseAPI.getUserById(cwSkd.getYwName());
            TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
            templateMessageDTO.setFromUser("管理员");
            templateMessageDTO.setToUser(cwSkd.getShName() + ",");
            templateMessageDTO.setTitle(TITLE);
            templateMessageDTO.setTemplateCode("order");
            Map<String, String> templateParam = new HashMap<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String str = simpleDateFormat.format(new Date());
            templateParam.put("ts_date", str);
            templateParam.put("ts_content", getMessage(user != null?user.getRealname():"该业务员不存在！", str));
            templateParam.put("checkOrder", cwSkd.getSkNo());
            templateParam.put("cd_url", "/yunxiao/collection/CwYskdList");
            templateMessageDTO.setTemplateParam(templateParam);
            sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;

        }
    }

    @Override
    @Transactional
    public boolean addSkd(JSONObject jsonObject, HttpServletRequest req) {
        try {
            CwSaleInvoice csi = JSON.parseObject(jsonObject.toJSONString(), CwSaleInvoice.class);
            CwSkd cs = JSON.parseObject(jsonObject.toJSONString(), CwSkd.class);
//            if (csi.getSyysJine().compareTo(csi.getSupamount()) == 1) {
//                return Result.error("本次使用预收金额不能大于剩余开票金额" + csi.getSupamount() + "!");
//            }
            String max_code = cwSkdMapper.getMaxCode();
            Map<String, String> codeMap = new HashMap<>();
            if (max_code == null) {
                codeMap.put("maxCode", null);
            } else {
                codeMap.put("maxCode", max_code);
            }
            String tenantId = req.getHeader("tenant-id");
            String tname = soSaleOrderMapper.getTname(tenantId);

            String name = tname + "SK_";
            String xssk = generateOddUtil.createCode(codeMap, name);

            CwSaleInvoice cwSaleInvoice = cwSaleInvoiceMapper.getByInvoiceNo(csi.getInvoiceNo());
            if (csi.getSrNo() != null && csi.getSrNo() != "" && !csi.getSrNo().isEmpty()) {
                CwSkd cskd = cwSkdMapper.getByskNo(csi.getSrNo());
                CwSkd yskdx = new CwSkd();
                yskdx.setSkNo(xssk.substring(0, 2) + "DK" + xssk.substring(4));
                yskdx.setSosNo(csi.getSosNo());
                yskdx.setFpNo(csi.getInvoiceNo());
                yskdx.setJsType(csi.getJsType());
                yskdx.setZhName(csi.getZhName());
                yskdx.setJsCustom(csi.getSoCustom());
                yskdx.setSosNum(csi.getFpsl());
                yskdx.setSosAmount(csi.getHsje());
                yskdx.setSosPrice(csi.getHsdj());
                yskdx.setSosNotax(csi.getWsje());
                yskdx.setYwName(csi.getPoStaff());
                yskdx.setDept(cs.getDept());
                yskdx.setSoNo(csi.getSoNo());
                yskdx.setYwType("4");
                yskdx.setSyys("0");
                yskdx.setIsDelete(0);
                yskdx.setSoStatus(0);
                yskdx.setTradecode(cs.getTradecode());
                if (csi.getSyysJine().compareTo(BigDecimal.valueOf(0)) > -1) { //>=0
                    if (cs.getLsJine() == null) {  //本次使用预收金额=cs.getSkJinen()
                        cskd.setSkJinen(cskd.getSkJinen().subtract(cs.getSkJinen()));//=0
                        cwSaleInvoice.setSupamount(cwSaleInvoice.getSupamount().subtract(csi.getSyysJine()).subtract(cs.getSkJinen()));
                        if (cwSaleInvoice.getSyysJine() == null) {    //发票使用预收金额，
                            cwSaleInvoice.setSyysJine(cs.getSkJinen());
                        } else {
                            cwSaleInvoice.setSyysJine(cwSaleInvoice.getSyysJine().add(cs.getSkJinen()));
                        }
                        yskdx.setSkJinen(cs.getSkJinen());
                        cs.setSkJinen(csi.getSyysJine());//选择预收款单后，如果临时字段LsJine为null,则剩余预收款金额全部抵消
                        cs.setSyyskJine(yskdx.getSkJinen());
                        cs.setZskJine(cs.getSyyskJine().add(cs.getSkJinen()));

                    } else {   //本次使用预收金额=cs.getLsJine()
                        cskd.setSkJinen(cskd.getSkJinen().subtract(cs.getLsJine()));
                        cwSaleInvoice.setSupamount(cwSaleInvoice.getSupamount().subtract(cs.getLsJine()).subtract(csi.getSyysJine()));
                        if (cwSaleInvoice.getSyysJine() == null) { //发票使用预收金额
                            cwSaleInvoice.setSyysJine(cs.getLsJine());
                        } else {
                            cwSaleInvoice.setSyysJine(cwSaleInvoice.getSyysJine().add(cs.getLsJine()));
                        }
                        yskdx.setSkJinen(cs.getLsJine());
                        cs.setSkJinen(csi.getSyysJine());
                        cs.setSyyskJine(cs.getLsJine());
                        cs.setZskJine(cs.getSyyskJine().add(cs.getSkJinen()));

                    }
//                    if (cwSaleInvoice.getSupamount().compareTo(BigDecimal.valueOf(0)) < 1) {   //<=0
//                        cwSaleInvoice.setIsSkd(1);
//                    }
                    cwSaleInvoice.setSrNo(csi.getSrNo());
                    cwSkdMapper.updateById(cskd);
                    cwSaleInvoiceMapper.updateById(cwSaleInvoice);
                    yskdx.setSkJinee(yskdx.getSkJinen());
                    yskdx.setBjJine(yskdx.getSkJinen());
                    yskdx.setPuCdate(new Date());
                    yskdx.setCreateTime(new Date());
                    yskdx.setSyyskNo(csi.getSrNo());
                    cwSkdMapper.insert(yskdx);

//                    return Result.OK("使用预收抵消发票金额成功，无须新增收款单!");

                    cs.setId("");
                    cs.setSkNo(xssk);
//                    cs.setSosNo(csi.getSosNo());
//                    cs.setFpNo(csi.getInvoiceNo());
                    cs.setSrNo(yskdx.getSkNo());//使用预收款单
                    cs.setSkJinee(cs.getSkJinen());
                    cs.setJsType(csi.getJsType());
                    cs.setZhName(csi.getZhName());
                    cs.setJsCustom(csi.getSoCustom());
//                    cs.setSosNum(csi.getFpsl());
                    cs.setSosAmount(csi.getHsje());
                    cs.setSosPrice(csi.getHsdj());
                    cs.setSosNotax(csi.getWsje());
                    cs.setYwName(csi.getPoStaff());
                    cs.setSoNo(csi.getSoNo());
                    cs.setYwType("1");
                    cs.setSyys("1");
                    cs.setIsDelete(0);
                    cs.setSoStatus(0);
                    cs.setBjJine(cs.getSkJinen());
                    cs.setPuCdate(new Date());
                    cs.setCreateTime(new Date());
                    cs.setSyyskNo(csi.getSrNo());
                    cs.setBjSyyskno(cs.getSyyskNo());
                    cs.setBjYskjine(cs.getSyyskJine());
                    cwSkdMapper.insert(cs);


                    LoginUser user = sysBaseAPI.getUserById(cs.getYwName());
                    TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
                    templateMessageDTO.setFromUser("管理员");
                    templateMessageDTO.setToUser(cs.getShName() + ",");
                    templateMessageDTO.setTitle(TITLE);
                    templateMessageDTO.setTemplateCode("order");
                    Map<String, String> templateParam = new HashMap<>();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String date = simpleDateFormat.format(new Date());
                    templateParam.put("ts_date", date);
                    templateParam.put("ts_content", getMessage(user != null?user.getRealname():"该业务员不存在！", date));
                    templateParam.put("checkOrder", cs.getSkNo());
                    templateParam.put("cd_url", "/collection/CwSkdList/list");
                    templateMessageDTO.setTemplateParam(templateParam);
                    sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);

//                    return Result.OK("使用预收已抵消发票金额,并生成收款单成功!");
                }

            } else {
                if (csi.getSyysJine().compareTo(BigDecimal.valueOf(0)) == 1) {
                    cs.setId("");
                    cs.setSkNo(xssk);
                    cs.setSosNo(csi.getSosNo());
//			 String soSaleOrder = soSettlementService.getBySosNo(csi.getSosNo());
                    cs.setFpNo(csi.getInvoiceNo());
                    cs.setSkJinen(csi.getSyysJine());
                    cs.setSkJinee(cs.getSkJinen());
                    cs.setJsType(csi.getJsType());
                    cs.setZhName(csi.getZhName());
                    cs.setJsCustom(csi.getSoCustom());
                    cs.setSosNum(csi.getFpsl());
                    cs.setSosAmount(csi.getHsje());
                    cs.setSosPrice(csi.getHsdj());
                    cs.setSosNotax(csi.getWsje());
                    cs.setYwName(csi.getPoStaff());
                    cs.setSoNo(csi.getSoNo());
                    cs.setSkJinee(cs.getSkJinen());
                    cs.setYwType("1");
                    cs.setSyys("0");
                    cs.setIsDelete(0);
                    cs.setSoStatus(0);
                    cs.setBjJine(cs.getSkJinen());
                    cs.setPuCdate(new Date());
                    cs.setCreateTime(new Date());
                    cs.setZskJine(cs.getSkJinen());
                    cs.setBjSyyskno(cs.getSyyskNo());
                    cs.setBjYskjine(cs.getSyyskJine());
                    cwSkdMapper.insert(cs);

                    LoginUser user = sysBaseAPI.getUserById(cs.getYwName());
                    TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
                    templateMessageDTO.setFromUser("管理员");
                    templateMessageDTO.setToUser(cs.getShName() + ",");
                    templateMessageDTO.setTitle(TITLE);
                    templateMessageDTO.setTemplateCode("order");
                    Map<String, String> templateParam = new HashMap<>();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String date = simpleDateFormat.format(new Date());
                    templateParam.put("ts_date", date);
                    templateParam.put("ts_content", getMessage(user != null?user.getRealname():"该业务员不存在！", date));
                    templateParam.put("checkOrder", cs.getSkNo());
                    templateParam.put("cd_url", "/collection/CwSkdList/list");
                    templateMessageDTO.setTemplateParam(templateParam);
                    sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);

                    cwSaleInvoice.setSupamount(cwSaleInvoice.getSupamount().subtract(csi.getSyysJine()));

                    if (cwSaleInvoice.getSupamount().compareTo(BigDecimal.valueOf(0)) < 1) {   //<=0
                        cwSaleInvoice.setIsSkd(1);
                    }
                    cwSaleInvoiceMapper.updateById(cwSaleInvoice);

//                    cwSaleInvoice.setSyysJine(cwSaleInvoice.getSyysJine());
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;

        }
    }

    @Override
    public Page<CwSkd> getList(Page<CwSkd> page, QueryWrapper<CwSkd> queryWrapper) {
        return page.setRecords(cwSkdMapper.getList(page, queryWrapper));
    }



    @Override
    @Transactional
    public boolean edit(CwSkd cwSkd) {
        try {
            CwSaleInvoice c = cwSaleInvoiceMapper.getByInvoiceNo(cwSkd.getFpNo());
            YxQcysOrder qc = yxQcysOrderMapper.getByQcskNo(cwSkd.getQcskNo());

            if (c!= null) {
                if ("1".equals(cwSkd.getSyys())) { //使用预收的
                    CwSkd skdk = cwSkdMapper.getByskNo(cwSkd.getSrNo()); //修改预收款抵扣单

                    if (!cwSkd.getSyyskNo().equals(cwSkd.getBjSyyskno())) {     //预收款单改变,
                        CwSkd skd = cwSkdMapper.getByskNo(cwSkd.getBjSyyskno());//预收款单,之前的

                        skd.setSkJinen(skd.getSkJinen().add(cwSkd.getBjYskjine()));

                        cwSkdMapper.updateById(skd);

                        CwSkd sk = cwSkdMapper.getByskNo(cwSkd.getSyyskNo()); //编辑后的
                        sk.setSkJinen(sk.getSkJinen().subtract(cwSkd.getSyyskJine()));
                        cwSkdMapper.updateById(sk);

                    } else {
                        CwSkd skd = cwSkdMapper.getByskNo(cwSkd.getSyyskNo());
                        skd.setSkJinen(skd.getSkJinen().add(cwSkd.getBjYskjine().subtract(cwSkd.getSyyskJine())));

                        cwSkdMapper.updateById(skd);

                    }
                    skdk.setSkJinen(cwSkd.getSyyskJine());
                    skdk.setSyyskNo(cwSkd.getSyyskNo());
                    c.setSupamount(c.getSupamount()
                            .add(cwSkd.getBjJine().subtract(cwSkd.getSkJinen()))
                            .add(cwSkd.getBjYskjine().subtract(cwSkd.getSyyskJine())));
                    cwSkdMapper.updateById(skdk);

                } else {

                    c.setSupamount(c.getSupamount()
                            .add(cwSkd.getBjJine().subtract(cwSkd.getSkJinen())));
                }
                cwSaleInvoiceMapper.updateById(c);
            }
            if (qc!= null) {
                if ("1".equals(cwSkd.getSyys())) { //使用预收的
                    CwSkd skdk = cwSkdMapper.getByskNo(cwSkd.getSrNo()); //修改预收款抵扣单

                    if (!cwSkd.getSyyskNo().equals(cwSkd.getBjSyyskno())) {     //预收款单改变,
                        CwSkd skd = cwSkdMapper.getByskNo(cwSkd.getBjSyyskno());//预收款单,之前的

                        skd.setSkJinen(skd.getSkJinen().add(cwSkd.getBjYskjine()));

                        cwSkdMapper.updateById(skd);

                        CwSkd sk = cwSkdMapper.getByskNo(cwSkd.getSyyskNo()); //编辑后的
                        sk.setSkJinen(sk.getSkJinen().subtract(cwSkd.getSyyskJine()));
                        cwSkdMapper.updateById(sk);

                    } else {
                        CwSkd skd = cwSkdMapper.getByskNo(cwSkd.getSyyskNo());
                        skd.setSkJinen(skd.getSkJinen().add(cwSkd.getBjYskjine().subtract(cwSkd.getSyyskJine())));

                        cwSkdMapper.updateById(skd);

                    }
                    skdk.setSkJinen(cwSkd.getSyyskJine());
                    skdk.setSyyskNo(cwSkd.getSyyskNo());
                    qc.setSurplusJine(qc.getSurplusJine()
                            .add(cwSkd.getBjJine().subtract(cwSkd.getSkJinen()))
                            .add(cwSkd.getBjYskjine().subtract(cwSkd.getSyyskJine())));
                    cwSkdMapper.updateById(skdk);

                } else {
                    qc.setSurplusJine(qc.getSurplusJine()
                            .add(cwSkd.getBjJine().subtract(cwSkd.getSkJinen())));
                }
                yxQcysOrderMapper.updateById(qc);
            }

            if (cwSkd.getSyyskJine() == null){
                cwSkd.setZskJine(cwSkd.getSkJinen());
            }else {
                cwSkd.setZskJine(cwSkd.getSkJinen().add(cwSkd.getSyyskJine()));
            }
            cwSkd.setBjYskjine(cwSkd.getSyyskJine());
            cwSkd.setBjJine(cwSkd.getSkJinen());
            cwSkd.setBjSyyskno(cwSkd.getSyyskNo());
            cwSkdMapper.updateById(cwSkd);

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }
    }


    @Override
    @Transactional
    public boolean addQcSkd(JSONObject jsonObject, HttpServletRequest req) {
        try {
            CwSaleInvoice csi = JSON.parseObject(jsonObject.toJSONString(), CwSaleInvoice.class);
            CwSkd cs = JSON.parseObject(jsonObject.toJSONString(), CwSkd.class);
            YxQcysOrder qc = JSON.parseObject(jsonObject.toJSONString(), YxQcysOrder.class);

            String max_code = cwSkdMapper.getMaxCode();
            Map<String, String> codeMap = new HashMap<>();
            if (max_code == null) {
                codeMap.put("maxCode", null);
            } else {
                codeMap.put("maxCode", max_code);
            }
            String tenantId = req.getHeader("tenant-id");
            String tname = soSaleOrderMapper.getTname(tenantId);

            String name = tname + "SK_";
            String xssk = generateOddUtil.createCode(codeMap, name);

//            CwSaleInvoice cwSaleInvoice = cwSaleInvoiceMapper.getByInvoiceNo(csi.getInvoiceNo());
            YxQcysOrder qcsk = yxQcysOrderMapper.getByQcskNo(cs.getQcskNo());
            if (csi.getSrNo() != null && csi.getSrNo() != "" && !csi.getSrNo().isEmpty()) {
                CwSkd cskd = cwSkdMapper.getByskNo(csi.getSrNo());
                CwSkd yskdx = new CwSkd();
                yskdx.setSkNo(xssk.substring(0, 2) + "DK" + xssk.substring(4));
                yskdx.setSosNo(csi.getSosNo());///////////////////////////
                yskdx.setFpNo(csi.getInvoiceNo());
                yskdx.setJsType(csi.getJsType());
                yskdx.setZhName(csi.getZhName());
                yskdx.setJsCustom(csi.getSoCustom());
                yskdx.setSosNum(csi.getFpsl());
                yskdx.setSosAmount(csi.getHsje());
                yskdx.setSosPrice(csi.getHsdj());
                yskdx.setSosNotax(csi.getWsje());
                yskdx.setYwName(csi.getPoStaff());
                yskdx.setDept(cs.getDept());
                yskdx.setSoNo(csi.getSoNo());
                yskdx.setYwType("4");
                yskdx.setSyys("0");
                yskdx.setIsDelete(0);
                yskdx.setSoStatus(0);
                yskdx.setTradecode(cs.getTradecode());
                if (csi.getSyysJine().compareTo(BigDecimal.valueOf(0)) > -1) { //>=0
                    if (cs.getLsJine() == null) {  //本次使用预收金额=cs.getSkJinen()
                        cskd.setSkJinen(cskd.getSkJinen().subtract(cs.getSkJinen()));//=0
                        qcsk.setSurplusJine(qcsk.getSurplusJine().subtract(csi.getSyysJine()).subtract(cs.getSkJinen()));
//                        if (cwSaleInvoice.getSyysJine() == null) {    //发票使用预收金额，
//                            cwSaleInvoice.setSyysJine(cs.getSkJinen());
//                        } else {
//                            cwSaleInvoice.setSyysJine(cwSaleInvoice.getSyysJine().add(cs.getSkJinen()));
//                        }
                        yskdx.setSkJinen(cs.getSkJinen());
                        cs.setSkJinen(csi.getSyysJine());//选择预收款单后，如果临时字段LsJine为null,则剩余预收款金额全部抵消
                        cs.setSyyskJine(yskdx.getSkJinen());
                        cs.setZskJine(cs.getSyyskJine().add(cs.getSkJinen()));

                    } else {   //本次使用预收金额=cs.getLsJine()
                        cskd.setSkJinen(cskd.getSkJinen().subtract(cs.getLsJine()));
//                        cwSaleInvoice.setSupamount(cwSaleInvoice.getSupamount().subtract(cs.getLsJine()).subtract(csi.getSyysJine()));
                        qcsk.setSurplusJine(qcsk.getSurplusJine().subtract(cs.getLsJine()).subtract(csi.getSyysJine()));
//                        if (cwSaleInvoice.getSyysJine() == null) { //发票使用预收金额
//                            cwSaleInvoice.setSyysJine(cs.getLsJine());
//                        } else {
//                            cwSaleInvoice.setSyysJine(cwSaleInvoice.getSyysJine().add(cs.getLsJine()));
//                        }
                        yskdx.setSkJinen(cs.getLsJine());
                        cs.setSkJinen(csi.getSyysJine());
                        cs.setSyyskJine(cs.getLsJine());
                        cs.setZskJine(cs.getSyyskJine().add(cs.getSkJinen()));

                    }
//                    if (cwSaleInvoice.getSupamount().compareTo(BigDecimal.valueOf(0)) < 1) {   //<=0
//                        cwSaleInvoice.setIsSkd(1);
//                    }
//                    cwSaleInvoice.setSrNo(csi.getSrNo());
                    cwSkdMapper.updateById(cskd);
                    yxQcysOrderMapper.updateById(qcsk);
                    yskdx.setSkJinee(yskdx.getSkJinen());
                    yskdx.setBjJine(yskdx.getSkJinen());
                    yskdx.setPuCdate(new Date());
                    yskdx.setCreateTime(new Date());
                    yskdx.setSyyskNo(csi.getSrNo());
                    cwSkdMapper.insert(yskdx);

//                    return Result.OK("使用预收抵消发票金额成功，无须新增收款单!");

                    cs.setId("");
                    cs.setSkNo(xssk);
                    cs.setSosNo(csi.getSosNo());
                    cs.setFpNo(csi.getInvoiceNo());
                    cs.setSrNo(yskdx.getSkNo());//使用预收款单
                    cs.setSkJinee(cs.getSkJinen());
                    cs.setJsType(csi.getJsType());
                    cs.setZhName(csi.getZhName());
                    cs.setJsCustom(csi.getSoCustom());
                    cs.setSosNum(csi.getFpsl());
                    cs.setSosAmount(csi.getHsje());
                    cs.setSosPrice(csi.getHsdj());
                    cs.setSosNotax(csi.getWsje());
                    cs.setYwName(csi.getPoStaff());
                    cs.setSoNo(csi.getSoNo());
                    cs.setYwType("5");
                    cs.setSyys("1");
                    cs.setIsDelete(0);
                    cs.setSoStatus(0);
                    cs.setBjJine(cs.getSkJinen());
                    cs.setPuCdate(new Date());
                    cs.setCreateTime(new Date());
                    cs.setSyyskNo(csi.getSrNo());
                    cs.setBjSyyskno(cs.getSyyskNo());
                    cs.setBjYskjine(cs.getSyyskJine());
                    cwSkdMapper.insert(cs);


                    LoginUser user = sysBaseAPI.getUserById(cs.getYwName());
                    TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
                    templateMessageDTO.setFromUser("管理员");
                    templateMessageDTO.setToUser(cs.getShName() + ",");
                    templateMessageDTO.setTitle(TITLE);
                    templateMessageDTO.setTemplateCode("order");
                    Map<String, String> templateParam = new HashMap<>();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String date = simpleDateFormat.format(new Date());
                    templateParam.put("ts_date", date);
                    templateParam.put("ts_content", getMessage(user != null?user.getRealname():"该业务员不存在！", date));
                    templateParam.put("checkOrder", cs.getSkNo());
                    templateParam.put("cd_url", "/collection/CwSkdList/list");
                    templateMessageDTO.setTemplateParam(templateParam);
                    sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);

//                    return Result.OK("使用预收已抵消发票金额,并生成收款单成功!");
                }

            } else {
                if (csi.getSyysJine().compareTo(BigDecimal.valueOf(0)) == 1) {
                    cs.setId("");
                    cs.setSkNo(xssk);
                    cs.setSosNo(csi.getSosNo());
//			 String soSaleOrder = soSettlementService.getBySosNo(csi.getSosNo());
                    cs.setFpNo(csi.getInvoiceNo());
                    cs.setSkJinen(csi.getSyysJine());
                    cs.setSkJinee(cs.getSkJinen());
                    cs.setJsType(csi.getJsType());
                    cs.setZhName(csi.getZhName());
                    cs.setJsCustom(csi.getSoCustom());
                    cs.setSosNum(csi.getFpsl());
                    cs.setSosAmount(csi.getHsje());
                    cs.setSosPrice(csi.getHsdj());
                    cs.setSosNotax(csi.getWsje());
                    cs.setYwName(csi.getPoStaff());
                    cs.setSoNo(csi.getSoNo());
                    cs.setSkJinee(cs.getSkJinen());
                    cs.setYwType("5");
                    cs.setSyys("0");
                    cs.setIsDelete(0);
                    cs.setSoStatus(0);
                    cs.setBjJine(cs.getSkJinen());
                    cs.setPuCdate(new Date());
                    cs.setCreateTime(new Date());
                    cs.setZskJine(cs.getSkJinen());
                    cs.setBjSyyskno(cs.getSyyskNo());
                    cs.setBjYskjine(cs.getSyyskJine());
                    cwSkdMapper.insert(cs);

                    LoginUser user = sysBaseAPI.getUserById(cs.getYwName());
                    TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
                    templateMessageDTO.setFromUser("管理员");
                    templateMessageDTO.setToUser(cs.getShName() + ",");
                    templateMessageDTO.setTitle(TITLE);
                    templateMessageDTO.setTemplateCode("order");
                    Map<String, String> templateParam = new HashMap<>();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String date = simpleDateFormat.format(new Date());
                    templateParam.put("ts_date", date);
                    templateParam.put("ts_content", getMessage(user != null?user.getRealname():"该业务员不存在！", date));
                    templateParam.put("checkOrder", cs.getSkNo());
                    templateParam.put("cd_url", "/collection/CwSkdList/list");
                    templateMessageDTO.setTemplateParam(templateParam);
                    sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);

                    qcsk.setSurplusJine(qcsk.getSurplusJine().subtract(csi.getSyysJine()));
//                    cwSaleInvoice.setSupamount(cwSaleInvoice.getSupamount().subtract(csi.getSyysJine()));

//                    if (cwSaleInvoice.getSupamount().compareTo(BigDecimal.valueOf(0)) < 1) {   //<=0
//                        cwSaleInvoice.setIsSkd(1);
//                    }
//                    cwSaleInvoiceMapper.updateById(cwSaleInvoice);
                    yxQcysOrderMapper.updateById(qcsk);

                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;

        }
    }

    @Override
    public Map<String, Double> getYskBytradecode(String tradecode) {
        return cwSkdMapper.getYskBytradecode(tradecode);
    }


    @Override
    public CwSkd getByskNo(String srNo) {
        return cwSkdMapper.getByskNo(srNo);
    }

    @Override
    public List<CwSkd> getBysoNo(String id) {
        return cwSkdMapper.getBysoNo(id);
    }

    @Override
    public List<CwSkd> getYskBysoNo(String id) {
        return cwSkdMapper.getYskBysoNo(id);
    }

    @Override
    public List<CwSkd> getByfpNo(String invoiceNo) {
        return cwSkdMapper.getByfpNo(invoiceNo);
    }
}
